﻿using qYun.Shared.Models;
using SqlSugar;

namespace qYun.ApiService.Services;

public class DbService:IDbService
{
    private readonly SqlSugarClient _sqlSugarClient;
    public DbService()
    {
        _sqlSugarClient = new SqlSugarClient(
             new ConnectionConfig()
             {
                 ConnectionString = "Server=localhost;Database=qYun;User=root;Password=123456;",
                 IsAutoCloseConnection = true,
                 DbType = DbType.MySql,
                 InitKeyType = InitKeyType.Attribute
             });
         // 创建数据库，若该库不存在，则创建
         _sqlSugarClient.DbMaintenance.CreateDatabase();
         //初始化数据表，若没有则创建
         _sqlSugarClient.CodeFirst.InitTables(typeof(GasModel));
         _sqlSugarClient.CodeFirst.InitTables(typeof(PlcModel));
         _sqlSugarClient.CodeFirst.InitTables(typeof(YunHeModel));

    }
    public async Task<List<YunHeModel>> GetYunHeDataAsync()
    {
        var data =await  _sqlSugarClient.Queryable<YunHeModel>().ToListAsync();
        return data;
    }
    public async Task<List<GasModel>> GetGasDataAsync()
    {
        var data =await _sqlSugarClient.Queryable<GasModel>().ToListAsync();
        return data;
    }
    public async Task<List<PlcModel>> GetPlcDataAsync()
    {
        var data = await _sqlSugarClient.Queryable<PlcModel>().ToListAsync();
        return data;
    }

    public async Task InsertYunheDataAyync(YunHeModel model)
    {
        await _sqlSugarClient.Insertable<YunHeModel>(model).ExecuteCommandAsync();
    }
    
    public async Task InsertGasDataAyync(GasModel model)
    {
        await _sqlSugarClient.Insertable<GasModel>(model).ExecuteCommandAsync();
    }
    
    public async Task InsertPlcDataAyync(PlcModel model)
    {
        await _sqlSugarClient.Insertable<PlcModel>(model).ExecuteCommandAsync();
    }
}

public interface IDbService
{
    public Task<List<YunHeModel>> GetYunHeDataAsync();
    public Task<List<GasModel>> GetGasDataAsync();
    public Task<List<PlcModel>> GetPlcDataAsync();
    public Task InsertYunheDataAyync(YunHeModel model);
    public Task InsertGasDataAyync(GasModel model);
    public Task InsertPlcDataAyync(PlcModel model);
}